package com.topideal.supplychain.hades.util;

import java.io.IOException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64Support {

    public static String toUrlStr(byte[] bytes) {

        String str = new BASE64Encoder().encode(bytes);

        if (str == null)
            return "";

        str = str.replaceAll("\\+", "_");
        str = str.replaceAll("/", "-");
        str = str.replaceAll("=", ".");
        str = str.replaceAll("\\s", "");

        return str;
    }

    public static String toStr(byte[] bytes) {

        String str = new BASE64Encoder().encode(bytes);

        if (str == null)
            return "";
        return str;
    }

    public static byte[] fromUrlStr(String str) throws IOException {

        if (str == null)
            return null;

        str = str.replaceAll("_", "+");
        str = str.replaceAll("-", "/");
        str = str.replaceAll("\\.", "=");

        byte[] dec = new BASE64Decoder().decodeBuffer(str);

        return dec;
    }

    public static byte[] fromStr(String str) throws IOException {

        if (str == null)
            return null;
        byte[] dec = new BASE64Decoder().decodeBuffer(str);

        return dec;
    }

}
